<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://iprintf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 朱龙 <iprintf@qq.com>
// +----------------------------------------------------------------------

use \think\Session;

// 应用公共文件
//
function html_element($type, $txt, $attr = null, $opt = [])
{
    $pro = '';

    if (isset($opt['class']))
        $pro .= ' class="'.$opt['class'].'"';
    else if ($type == 'button')
        $pro .= ' class="btn btn-default btn-primary"';

    if (isset($opt['id']))
        $pro .= ' id="'.$opt['id'].'"';

    if ($attr !== null)
        $pro .= ' '.$attr;

    if ($type == 'a') {
        $e = '<a href="javascript:void(0)"';
        $e .= $pro;
        $e .= '>'.$txt.'</a>';

    } else if ($type == 'button') {
        $e = '<button type="button"';
        $e .= $pro;
        $e .= '>'.$txt.'</button>';
    }

    return $e;
}

function html_link($url, $tag = '#datalist', $element = null, $txt = '链接', $confirm = null, $ajax = "true", $opt = [])
{
    $attr = ' kyo-link=\'';
    $attr .= '"url": "'.$url.'",';
    $attr .= '"ajax": '.$ajax;
    $attr .= ',"tag": "'.$tag.'"';
    if ($confirm !== null)
        $attr .= ',"confirm": "'.$confirm.'"';
    $attr .= '\'';

    if ($element !== null) {
        return html_element($element, $txt, $attr, $opt);
    }

    return $attr;
}

function html_pop($url, $w = null, $h = null, $title = null, $element = null, $txt = '弹出框', $opt = [])
{

    $attr = ' kyo-pop=\'';
    $attr .= '"url": "'.$url.'",';
    if ($w !== null)
        $attr .= '"w": '.$w;
    if ($h !== null)
        $attr .= ',"h": '.$h;
    if ($title !== null)
        $attr .= ',"title": "'.$title.'"';
    if (isset($opt['cover']))
        $attr .= ',"cover": "'.$opt['cover'].'"';
    if (isset($opt['bc']))
        $attr .= ',"bc": "'.$opt['bc'].'"';
    $attr .= '\'';

    if ($element !== null) {
        return html_element($element, $txt, $attr, $opt);
    }

    return $attr;
}

function sqlAll($sql)
{
    $data = \think\Db::query($sql);
    if (!is_array($data))
        return false;

    return $data;
}

function sqlRow($sql)
{
    $data = \think\Db::query($sql);
    if (!is_array($data) || count($data) == 0)
        return false;

    return $data[0];
}

function sqlCol($sql)
{
    $data = \think\Db::query($sql);
    if (!is_array($data) || count($data) == 0)
        return false;

    return current($data[0]);
}

function json_return($msg, $url = null, $tag = null, $close = null, $callback = null)
{
    if (is_array($msg)) {
        $json = $msg;
    } else {
        $json['msg'] = $msg;
        $url !== null && $json['url'] = $url;
        $tag !== null && $json['tag'] = $tag;
        $close !== null && $json['close'] = $close;
        $callback !== null && $json['callback'] = $callback;
    }

    return json($json);
}

function json_return_data($data, $type = 'html', $tag = null)
{
    return json([
            'type' => $type,
            'tag' => $tag,
            'data' => $data
        ]);
}

function json_return_refresh($msg, $data_id, $close = true, $callback = null)
{
    return json_return($msg, session($data_id.'.url'), '#'.$data_id, $close, $callback);
}

function check_login()
{
    if (session('?auth'))
        return false;

    $url = url('admin/Pub/login');
    if (request()->isAjax()) {
        $js_exit = 'layer.closeAll();';
        $js_exit .= 'layer.msg("登录超时", {time: 1000}, function(){';
        $js_exit .= 'location.href="'.$url.'";});';
        if (is_json())
            exit(json_encode(['callback' => $js_exit]));
        else
            exit('<script>'.$js_exit.'</script>');
    }
    header('location:'.$url);
    exit(0);
}

function curl($url, $data = null, $method = 'GET', $header = null)
{
    $curl = \kyoCurl::getInstrance();
    return $curl->send($url, $data, $method, $header);
}

function baidu_api($url, $method = 'GET', $data = null)
{
    $url = 'http://apis.baidu.com/apistore/'.$url;
    $header = [
        'apikey: '.config('baiduKey'),
    ];
    $s = curl($url, $data, $method, $header);
    if ($s === false)
        return false;
    return json_decode($s, true);
}

function get_ip_msg($ip)
{
    return baidu_api('iplookupservice/iplookup?ip='.$ip);
}

function send_mail($recv, $title, $body = null)
{
    $mail = \kyoMail::getInstrance();
    return $mail->sendTo($recv, $title, $body);
}

function aliyun_sms_url($phone, $content, $param = [])
{
    $secret = config('aliyun.secret');
    //默认值
    $defaultParam = [
        'RecNum' => $phone,
        'ParamString' => '{"name": "'.$content.'"}',
        'Action' => 'SingleSendSms',
        'Format' => 'JSON',
        'Version' => '2016-09-27',
        'SignatureVersion' => '1.0',
        'SignatureMethod' => 'HMAC-SHA1',
        'Timestamp' => gmdate('Y-m-d\TH:i:s\Z'),
        'SignatureNonce' => uniqid(),
        'AccessKeyId'   => config('aliyun.apikey'),
        'SignName'   => config('aliyun.sign_name'),
        'TemplateCode'   => config('aliyun.tpl_code'),
    ];
    //组合默认值
    $param = $param + $defaultParam;
    //按key排序
    ksort($param);

    //对key和value进行编码函数
	$percentEncode = function($str) {
	    $res = urlencode($str);
	    $res = preg_replace('/\+/', '%20', $res);
	    $res = preg_replace('/\*/', '%2A', $res);
	    $res = preg_replace('/%7E/', '~', $res);
	    return $res;
	};

    $sign_str = '';
    foreach ($param as $k => $v) {
        $sign_str .= $percentEncode($k).'='.$percentEncode($v).'&';
    }
    $sign_str = 'GET&%2F&'.$percentEncode(rtrim($sign_str, '&'));
    // echo $sign_str.'<br />';
    $sign = base64_encode(hash_hmac('sha1', $sign_str, $secret."&", true));
    // echo $sign.'<br />';

    $url_str = '';
    foreach ($param as $k => $v) {
        $url_str .= $k.'='.urlencode($v).'&';
    }
    $url = 'https://sms.aliyuncs.com?Signature='.$sign.'&'.rtrim($url_str, '&');
    // echo '<a href=\''.$url.'\'>'.$url.'</a>';
    return $url;
}

function aliyun_sms_send($phone, $content, $param = [])
{
    $json = curl(aliyun_sms_url($phone, $content, $param));
    if ($json === false)
        return false;
    return json_decode($json, true);
}


//判断ajax请求数据的格式
function is_json()
{
    if (isset($_SERVER['HTTP_ACCEPT'])
            && !strncasecmp($_SERVER['HTTP_ACCEPT'], 'application/json,', 17))
        return true;

    return false;
}

